//
//  SWEditorEffectToolbar.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/19.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit

protocol SWIEditorExpandToolbar:class
{
    weak var image:UIImage?{get set}
    weak var canvas:SWIMainCanvas?{get set}
    weak var delegate:SWEditorExpandToolbarDelegate?{get set}
}

class SWEditorExpandToolbar: UIView
{
    weak var image:UIImage?
    weak var canvas:SWIMainCanvas?
    weak var delegate:SWEditorExpandToolbarDelegate?
    
    func toolbarWillAppear(_ animated: Bool)
    {
        
    }
    
    func toolbarDidAppear(_ animated: Bool)
    {
        
    }
    
    func toolbarWillDisappear(_ animated: Bool)
    {
        
    }
    
    func toolbarDidDisappear(_ animated: Bool)
    {
        
    }
}

protocol SWEditorExpandToolbarDelegate:NSObjectProtocol
{
    //取消
    func expandToolbarCancel()
    
    //确定
    func expandToolbarConfirmed(_ image:UIImage)
}

class SWEditorEffectToolbar: SWEditorExpandToolbar,UICollectionViewDataSource,UICollectionViewDelegate,SWFilterDelegate
{
    //预览时将图片缩小到优化尺寸(单倍分辨率下的尺寸)
    var optimizationSize:CGSize = CGSizeZero
    
    private var _result:UIImage?
    private var _thumb:UIImage?
    
    //缓存磨皮过的图片以提高处理速度
    private var _skinSmoothImage:UIImage?
    
    private var _filters:[SWBaseFilter] = []
    private var _filter:SWBaseFilter?
    
    private let CellIdentifier:String = "InstaFiltersCollectionCell"
    private var _collectionView:UICollectionView?
    private var _confirmBtn:UIButton = UIButton(type: .custom)
    
    private var _change:Bool = false{
        didSet{
            if _change != oldValue
            {
                _confirmBtn.isEnabled = _change
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, frame.width, 124))
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        print("DEINIT SWEditorEffectToolbar")
    }
    
    override func toolbarDidAppear(_ animated: Bool)
    {
        print("toolbarDidAppear")
        if let image = image
        {
            //将图片缩小以加快滤镜的显示
            let originSize = image.originSize
            var scale = ViewUtil.getAdaptiveScale(originSize.width, targetH: originSize.height, containerW: optimizationSize.width, containerH: optimizationSize.height, inscribed: false)
            var size:CGSize = originSize
            if scale < 1
            {
                size = CGSizeMake(originSize.width * scale, originSize.height * scale)
            }
            //适中图
            _result = image.imageScaled(toConstrainSize: size) ?? image
            //print("_result:", _result?.size, _result?.scale)
            //缩略图
            scale = ViewUtil.getAdaptiveScale(originSize.width, targetH: originSize.height, containerW: 80, containerH: 80)
            size = CGSizeMake(originSize.width * scale, originSize.height * scale).multiply(UIScreen.main.scale)
            _thumb = image.imageScaled(toConstrainSize: size) ?? image
            
            _collectionView?.reloadData()
        }
    }
    
    private func setup()
    {
        _filters.append(SWNormalWhiteFilter())
        _filters.append(SWDeepWhiteFilter())
        _filters.append(SWMengHuanFilter())
        _filters.append(SWPinkFilter())
        _filters.append(SWRouHeFilter())
        _filters.append(SWMemoryFilter())
        _filters.append(SWAmaroFilter())
        _filters.append(SWLomoFilter())
        _filters.append(SWGrayscaleFilter())
        
        for filter in _filters
        {
            filter.delegate = self
        }
        
        let cancelBtn:UIButton = UIButton(type: .custom)
        cancelBtn.setImage(UIImage(named:"editor_icon_cancel"), for: .normal)
        cancelBtn.sizeToFit()
        cancelBtn.frame = CGRectMake(10, height - cancelBtn.height - 10, cancelBtn.width, cancelBtn.height)
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        addSubview(cancelBtn)
        
        let confirmBtn:UIButton = UIButton(type: .custom)
        confirmBtn.setImage(UIImage(named:"editor_icon_ok"), for: .normal)
        confirmBtn.sizeToFit()
        confirmBtn.frame = CGRectMake(width - confirmBtn.width - 10, height - confirmBtn.height - 10, confirmBtn.width, confirmBtn.height)
        confirmBtn.addTarget(self, action: #selector(confirmBtnTapped(_:)), for: .touchUpInside)
        addSubview(confirmBtn)
        _confirmBtn = confirmBtn
        _confirmBtn.isEnabled = false
        
        let collectionViewHeight:CGFloat = 84
        let ItemSize:CGSize = CGSizeMake(64, collectionViewHeight)
        let Grid:CGFloat = 3
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = ItemSize
        //横向最小间隔
        layout.minimumLineSpacing = Grid
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(0, Grid, 0, Grid)
        layout.scrollDirection = .horizontal
        
        //let collectionViewInsets = UIEdgeInsetsMake(0, 10, 0, 10)
        _collectionView = UICollectionView(frame: CGRectMake(0, 0, width, collectionViewHeight), collectionViewLayout: layout)
        _collectionView?.backgroundColor = backgroundColor
        _collectionView?.register(SWEffectCollectionCell.self, forCellWithReuseIdentifier: CellIdentifier)
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        addSubview(_collectionView!)
    }
    
    //执行滤镜
    private func execute(filter:SWBaseFilter)
    {
        if filter != _filter
        {
            _filter?.dispose()
            _filter = filter
            var info:[String:Any] = [:]
            if let skinSmoothImage = _skinSmoothImage{
                info[SWBaseFilter.SkinSmoothImageKey] = skinSmoothImage
            }
            
            if let image = _result
            {
                _filter?.execute(image: image, info:info)
                SVProgressHUD.show(withStatus: "处理中...")
            }
            
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return _filters.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell:SWEffectCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier:CellIdentifier, for: indexPath) as! SWEffectCollectionCell
        cell.thumb = _thumb
        cell.filter = _filters[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        _change = true
        if let filter = _filters.valueAt(indexPath.row)
        {
            execute(filter: filter)
        }
    }
    
    func filterProcessCompletion(_ filter:SWBaseFilter, image:UIImage, info:[String:Any]?)
    {
        if let skinSmoothImage = info?[SWBaseFilter.SkinSmoothImageKey] as? UIImage{
            _skinSmoothImage = skinSmoothImage
        }
        
        DispatchQueue.main.async {
            self.canvas?.image = image
            SVProgressHUD.dismiss()
        }
        
    }
    
    func filterProcessFail(_ filter:SWBaseFilter, error:NSError)
    {
        SVProgressHUD.dismiss()
    }
    
    @objc private func confirmBtnTapped(_ button:UIButton)
    {
        print("befort image:", image?.size, image?.scale)
        //aImage.size.multiply(aImage.scale)
        if let aImage = image,
           let fixImage = aImage.imageScaled(toConstrainSize: aImage.originSize),
           let filter = _filter, _change
        {
            print("fixImage:", fixImage.size, fixImage.scale)
            SVProgressHUD.show(withStatus: "处理中...")
            button.isEnabled = false
            
            let failCallback:((NSError)->Void) = {error in
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                }
            }
            
            let successCallback:((UIImage)->Void) = {[weak self] image in
                
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    print("处理后:", image.size, image.scale)
                    self?.delegate?.expandToolbarConfirmed(image)
                }
            }
            
            filter.execute(image: fixImage, info: nil, successCallback: successCallback, failCallback: failCallback)
        }
    }
    
    @objc private func cancelBtnTapped()
    {
        if _change
        {
            canvas?.image = image
        }
        delegate?.expandToolbarCancel()
    }
    
    
    
}
